package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dto.WmMaterialDto;
import com.heima.model.media.pojo.WmMaterial;
import com.heima.model.media.pojo.WmNewsMaterial;
import com.heima.model.media.pojo.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;
    @Value("${file.oss.profix}")
    String profix;
    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult upload_picture(MultipartFile multipartFile) {
        //1.校验参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件不存在");
        }
        //从WmThreadLocal中获取user
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.上传到aliyunOSS
        try {
            String oriName = multipartFile.getOriginalFilename();
            String suffix = oriName.substring(oriName.lastIndexOf("."));// .jpg
            //     生成文件的名称
            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            //     截图原始文件的后缀
            //     使用工具类上传到oss
            String fileUrl = fileStorageService.store(profix, fileName + suffix, multipartFile.getInputStream());
            //3. 创建素材表信息，将图片路径存入
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(wmUser.getId());
            wmMaterial.setUrl(fileUrl); // 设置oss中文件路径
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(new Date());
            //4. 将素材保存到数据库
            this.save(wmMaterial);
            wmMaterial.setUrl(webSite + fileUrl);
            //5. 封装返回结果
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件上传出现异常 ==> {}", e.getMessage());
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败");
        }
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.检查参数
        dto.checkParam();

        //2.构建查询条件
        Page<WmMaterial> pageReq = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQuery = Wrappers.<WmMaterial>lambdaQuery();
        //2.1 判断是否收藏
        if (dto.getIsCollection().intValue() == 1) {
            lambdaQuery.eq(WmMaterial::getIsCollection, 1);
        }
        //2.2获取user
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        lambdaQuery.eq(WmMaterial::getUserId, wmUser.getId());
        //按发布时间降序
        lambdaQuery.orderByDesc(WmMaterial::getCreatedTime);
        //3.查询
        IPage<WmMaterial> result = this.page(pageReq, lambdaQuery);
        List<WmMaterial> records = result.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        //4.响应
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal());
        responseResult.setData(records);
        return responseResult;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        //1.检验参数id
        if (null == id) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据id获取素材数据
        WmMaterial material = this.getById(id);
        if (material == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!material.getUserId().equals(wmUser.getId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //3.查看素材是否引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "数据被引用");
        }
        //4.删除素材(数据库)
        this.removeById(id);
        //5.删除素材(oss)
        fileStorageService.delete(material.getUrl());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short status) {
        //1.检验参数
        if (null == id) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (null == wmUser) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        this.update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,status)
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,wmUser.getId()));

        return ResponseResult.okResult();
    }
}

